﻿using DFGK.IRepository;
using DFGK.IService;
using DFGK.Service;
using DFGK_WMS.Common;
using DFGK_WMS.Model.Dto;
using DFGK_WMS.Model.Dto.YS;
using DFGK_WMS.Model.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NPOI.SS.Formula.Atp;
using NPOI.XWPF.UserModel;

namespace DFGK_WMS.WebAPI.Controllers.FengRenErp
{
    /// <summary>
    /// erp对接
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ERPSystemController : BaseController
    {
        private readonly IMaterialService materialService;
        private readonly IInventoryLogService inventoryLogService;
        private readonly ISupplierService supplierService;
        private readonly HttpClientHelper _httpClientHelper;
        private readonly IReceivingOrderDetailService receivingOrderDetailService;
        private readonly IMaterialPackageReceivingService materialPackageReceivingService;
        private readonly IEmployeeService employeeService;
        private readonly IDepartMentService departMentService;
        private readonly ICustomerService customerService;
        private readonly IAreaService areaService;
        private readonly IUnitService unitService;
        private readonly IOtherTypeService otherTypeService;
        private readonly IStockService stockService;
        private readonly IReceivingBillService receivingBillService;
        private readonly IShippingOrderDetailService shippingOrderDetailService;




        public ERPSystemController(IWebHostEnvironment environment, ISupplierService supplierService, IMaterialService materialService, IReceivingBillService receivingBillService, IShippingOrderDetailService shippingOrderDetailService, IMaterialPackageReceivingService materialPackageReceivingService, IInventoryLogService inventoryLogService, IReceivingOrderDetailService receivingOrderDetailService, HttpClientHelper httpClientHelper, IAreaService areaService, IEmployeeService employeeService, IDepartMentService departMentService, ICustomerService customerService, IStockService stockService, IUnitService unitService, IOtherTypeService otherTypeService) : base(environment)
        {
            this.supplierService = supplierService;
            this.materialService = materialService;
            this.receivingBillService = receivingBillService;
            this.shippingOrderDetailService = shippingOrderDetailService;
            this.materialPackageReceivingService = materialPackageReceivingService;
            this.inventoryLogService = inventoryLogService;
            this.receivingOrderDetailService = receivingOrderDetailService;
            _httpClientHelper = httpClientHelper;
            this.areaService = areaService;
            this.employeeService = employeeService;
            this.departMentService = departMentService;
            this.customerService = customerService;
            this.stockService = stockService;
            this.unitService = unitService;
            this.otherTypeService = otherTypeService;
        }
        /// <summary>
        /// wms删除erp收货
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelMaterialPackReceivingById(long id)
        {
            if (id < 1)
            {
                return Ok(BaseResult.Result("400", "id不能为空！"));
            }
            var delById = materialPackageReceivingService.DelMaterialPackageReceiving(id);
            if (delById)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));

        }
        /// <summary>
        /// 添加部门主数据
        /// </summary>
        /// <param name="employee"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddDepartmentList(List<Department> department)
        {
            if (department.Count < 1)
            {
                return Ok(BaseResult.Result("400", "数据为空！"));
            }
            string message = "";
            var res = departMentService.AddDepartMentList(department, out message);
            if (res)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！" + message, "500"));
        }
       /// <summary>
       /// 添加员工主数据
       /// </summary>
       /// <param name="employee"></param>
       /// <returns></returns>
        [HttpPost]
        public IActionResult AddEmployeeList(List<Employee> employee)
        {
            if (employee.Count < 1)
            {
                return Ok(BaseResult.Result("400", "数据为空！"));
            }
            string message = "";
            var res = employeeService.AddEmployeeList(employee, out message);
            if (res)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！" + message, "500"));
        }
        /// <summary>
        /// 添加仓库主数据
        /// </summary>
        /// <param name="stocks"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddStockList(List<Stock> stocks)
        {
            if (stocks.Count < 1)
            {
                return Ok(BaseResult.Result("400", "数据为空！"));
            }
            string message = "";
            var res = stockService.AddStockList(stocks, out message);
            if (res)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！" + message, "500"));
        }

        /// <summary>
        /// 添加客户主数据
        /// </summary>
        /// <param name="employee"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddCustomerList(List<Customer> customer)
        {
            if (customer.Count < 1)
            {
                return Ok(BaseResult.Result("400", "数据为空！"));
            }
            string message = "";
            var res = customerService.AddCustomerList(customer, out message);
            if (res)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！" + message, "500"));
        }


        /// <summary>
        /// 添加供应商主数据
        /// </summary>
        /// <param name="supplier"></param> 
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddSupplierList(List<Supplier> supplier)
        {
            if (supplier.Count < 1)
            {
                return Ok(BaseResult.Result("400", "数据为空！"));
            }
            string message = "";
            var res = supplierService.AddSupplierList(supplier, out message);
            if (res)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！" + message, "500"));
        }
        /// <summary>
        /// 添加计量单位主数据
        /// </summary>
        /// <param name="supplier"></param> 
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddUnitList(List<Unit> units)
        {
            if (units.Count < 1)
            {
                return Ok(BaseResult.Result("400", "数据为空！"));
            }
            string message = "";
            var res = unitService.AddUnitList(units, out message);
            if (res)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！" + message, "500"));
        }

        /// <summary>
        /// 添加单据类型主数据
        /// </summary>
        /// <param name="supplier"></param> 
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddOtherType(List<OtherType> otherTypes)
        {
            if (otherTypes.Count < 1)
            {
                return Ok(BaseResult.Result("400", "数据为空！"));
            }
            string message = "";
            var res = otherTypeService.AddOtherTypeList(otherTypes, out message);
            if (res)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！" + message, "500"));
        }
        /// <summary>
        /// 同步物料
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddMaterialList(List<Material> m)
        {
            if (m.Count < 1)
            {
                return Ok(BaseResult.Result("400", "数据为空！"));
            }
            string message = "";
            var IsOk = materialService.AddMaterialList(m, out message);
            if (IsOk)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！", "500"));
        }
        /// <summary>
        /// 添加仓位主数据
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddCellList(List<Material> m)
        {
            if (m.Count < 1)
            {
                return Ok(BaseResult.Result("400", "数据为空！"));
            }
            string message = "";
            var IsOk = materialService.AddMaterialList(m, out message);
            if (IsOk)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！", "500"));
        }


        /// <summary>
        /// Erp下发入库单据(采购单和收料通知单)
        /// </summary>
        /// <param name="eBSReceivingBill"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddErpReceivingBill(ERPReceivingBillDTO ids)
        {
            if (string.IsNullOrEmpty(ids.BillNo))
            {
                return Ok(BaseResult.Result("400", "单号不能为空！"));
            }

            string message = "";

            bool IsOK = materialPackageReceivingService.AddOrModefiyMaterialPackageReceiving(ids, out message);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！" + message, "500"));
        }
        /// <summary>
        /// Erp下发入库单据(生产任务单)
        /// </summary>
        /// <param name="eBSReceivingBill"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddErpProductionOrder(ERPProductionOrderDto ids)
        {
            if (string.IsNullOrEmpty(ids.BillNo))
            {
                return Ok(BaseResult.Result("400", "单号不能为空！"));
            }

            string message = "";

            bool IsOK = materialPackageReceivingService.AddProductionOrder(ids, out message);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！" + message, "500"));
        }


        /// <summary>
        /// Erp下发出库单据(生产投料单 或 生产报废补料单)
        /// </summary>
        /// <param name="eBSShippingOrder"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddErpAddShippingOrder(ErpShippingOrderDTO erpShippingOrder)
        {
            if (string.IsNullOrEmpty(erpShippingOrder.BillNo))
            {
                return Ok(BaseResult.Result("400", "订单编号不能为空！"));
            }
            if (erpShippingOrder.items.Count() <= 0)
            {
                return Ok(BaseResult.Result("400", "订单项不能为空！"));
            }
            var IsOk = shippingOrderDetailService.ERPAddShippingOrderDetail(erpShippingOrder, out string message);
            if (IsOk)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！" + message, "500"));
        }

        /// <summary>
        /// Erp下发仓库调拨单（成品发货部分）
        /// </summary>
        /// <param name="eBSShippingOrder"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddErpAddSendOrder(ErpSendOrderDTO erpsendorder)
        {
            if (string.IsNullOrEmpty(erpsendorder.BillNo))
            {
                return Ok(BaseResult.Result("400", "订单编号不能为空！"));
            }
            if (erpsendorder.items.Count() <= 0)
            {
                return Ok(BaseResult.Result("400", "订单项不能为空！"));
            }
            var IsOk = shippingOrderDetailService.ERPAddSendOrderDetail(erpsendorder, out string message);
            if (IsOk)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！" + message, "500"));
        }



        /// <summary>
        /// 获得入库的订单
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="orderSn"></param>
        /// <param name="status"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ERPGetReceivingInventoryFlow(List<ReceivingOrderDetailDto> dto)
        {
            if (dto != null)
            {
                
                try
                {
                    string jsonData = JsonConvert.SerializeObject(dto);
                    string targeUrl = "http://59.110.231.187:9883/api/FengRenERP/AddOrModefiyQuote";
                    // 调用 PostAsync 发送数据
                    string response = await _httpClientHelper.PostAsync(
                        url: targeUrl,
                        body: jsonData,
                        bodyMediaType: "application/json",  // 明确指定 JSON 类型
                        headers: new Dictionary<string, string>
                        {
                    { "X-Api-Key", "your-api-key" }  // 可选：添加认证头
                        }
                    );
                    // 如果 HTTP 请求成功，进行字段修改
                    if (!string.IsNullOrEmpty(response)) // 假设有返回值表示成功
                    {
                         receivingOrderDetailService.ModifyOutOrderNo(dto);
                        return Ok(BaseResult.Result(dto, "同步成功！", "200"));
                    }
                    else
                    {
                        // 如果HTTP返回为空或失败
                        return Ok(BaseResult.Result(null, "http为空同步失败！", "500", 0));
                    }
                }
                catch (Exception ex)
                {
                    // 捕获异常并返回失败信息
                    return Ok(BaseResult.Result(null, $"同步过程中发生错误: {ex.Message}", "500"));
                }
            }
            return Ok(BaseResult.Result(null, "同步失败！", "500", 0));
        }
        /// <summary>
        /// ERP获取出库单列表
        /// </summary>
        /// <param name="ordersn"></param>
        /// <param name="materialkey"></param>
        /// <param name="status"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult>  ERPGetShippingOrderDetailLockDtoList(List<ShippingOrderDetailLockDto> dto)
        {
            if (dto != null)
            {
                // 检查是否有已同步的记录
                var alreadySynced = dto.Any(item => item.PurOrderNo == "已同步");
                if (alreadySynced)
                {
                    // 如果集合中有已同步的OutOrderNo，返回错误信息
                    return Ok(BaseResult.Result(null, "存在已同步的数据，无法同步,请检查！", "400"));
                }
                var errorShippingOrder = dto.Any(item => item.Status < 4);
                if (errorShippingOrder)
                {
                    // 如果集合中有已同步的OutOrderNo，返回错误信息
                    return Ok(BaseResult.Result(null, "存在未完成的数据，无法同步,请检查！", "400"));
                }
                try
                {
                    string jsonData = JsonConvert.SerializeObject(dto);
                    string targeUrl = "";
                    // 调用 PostAsync 发送数据
                    string response = await _httpClientHelper.PostAsync(
                        url: targeUrl,
                        body: jsonData,
                        bodyMediaType: "application/json",  // 明确指定 JSON 类型
                        headers: new Dictionary<string, string>
                        {
                    { "X-Api-Key", "your-api-key" }  // 可选：添加认证头
                        }
                    );
                    // 如果 HTTP 请求成功，进行字段修改
                    if (!string.IsNullOrEmpty(response)) // 假设有返回值表示成功
                    {
                         shippingOrderDetailService.ModifyPurOrderNo(dto);
                        return Ok(BaseResult.Result(dto, "同步成功！", "200"));
                    }
                    else
                    {
                        // 如果HTTP返回为空或失败
                        return Ok(BaseResult.Result(null, "同步失败！", "500", 0));
                    }
                }
                catch (Exception ex)
                {
                    // 捕获异常并返回失败信息
                    return Ok(BaseResult.Result(null, $"同步过程中发生错误: {ex.Message}", "500"));
                }
            }
            return Ok(BaseResult.Result(null, "同步失败！", "500", 0));
        }



    }
}
